import './text.scss'
import { reqTextCorrection, reqRewrite } from '@/api/iFlytek'
import { useState, useRef, useEffect } from 'react'
import { InputNumber, Card, Input, message } from 'antd'
import dialogue from '@/utils/Ai'
import { WindowsOutlined, SearchOutlined } from '@ant-design/icons'
import { useSelector } from 'react-redux'
import SvgIcon from '@/components/SvgIcon'
import type { InputNumberProps } from 'antd'
import axios from 'axios'

function Text() {
  const limit = useSelector((state: any) => state.user.userInfo.authority)
  const [which, setWhich] = useState(4)
  const [asking, setAsking] = useState('')
  const [textCorr, setTextCorr] = useState('')
  const [output, setOutput] = useState<string>('')
  const ttsWSRef = useRef<WebSocket | null>(null)
  const totalResRef = useRef<string>('')
  const [liberty, setLiberty] = useState(6)
  const [isEnd, setIsEnd] = useState(true)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const [loading, setLoading] = useState(false)

  // 文本改写
  const rewrite = async (text: string, L: string = String(liberty)) => {
    const res = await reqRewrite({ L, text })
    setLoading(false)
    if (res.code === 200) {
      setOutput(JSON.parse(res.data)[0][0])
    }
  }
  // 文本纠错
  const textCorrection = async (text: string) => {
    const res = await reqTextCorrection({ text })
    setLoading(false)
    console.log(res)
    if (res.code === 200) {
      const data = JSON.parse(res.data)
      let answer = ''

      if (data.punc.length > 0) {
        answer += `<h3>标点错误：</h3><ul>`
        data.punc.forEach((item: any) => {
          answer += `<li>位置：${item[0]}，原标点：${item[1]}，建议标点：${item[2]}，错误类型：${item[3]}</li>`
        })
        answer += `</ul>`
      }

      if (data.char.length > 0) {
        answer += `<h3>错别字：</h3><ul>`
        data.char.forEach((item: any) => {
          answer += `<li>位置：${item[0]}，原字：${item[1]}，建议字：${item[2]}，错误类型：${item[3]}</li>`
        })
        answer += `</ul>`
      }

      if (data.word.length > 0) {
        answer += `<h3>错别词：</h3><ul>`
        data.word.forEach((item: any) => {
          answer += `<li>位置：${item[0]}，原词：${item[1]}，建议词：${item[2]}，错误类型：${item[3]}</li>`
        })
        answer += `</ul>`
      }

      if (data.redund.length > 0) {
        answer += `<h3>冗余：</h3><ul>`
        data.redund.forEach((item: any) => {
          answer += `<li>位置：${item[0]}，冗余词：${item[1]}</li>`
        })
        answer += `</ul>`
      }

      if (data.miss.length > 0) {
        answer += `<h3>缺失：</h3><ul>`
        data.miss.forEach((item: any) => {
          answer += `<li>位置：${item[0]}，缺失内容：${item[1]}</li>`
        })
        answer += `</ul>`
      }

      if (data.order.length > 0) {
        answer += `<h3>乱序：</h3><ul>`
        data.order.forEach((item: any) => {
          answer += `<li>位置：${item[0]}，内容：${item[1]}</li>`
        })
        answer += `</ul>`
      }

      if (data.dapei.length > 0) {
        answer += `<h3>搭配错误：</h3><ul>`
        data.dapei.forEach((item: any) => {
          answer += `<li>位置：${item[0]}，错误搭配：${item[1]}，建议搭配：${item[2]}</li>`
        })
        answer += `</ul>`
      }

      if (data.idm.length > 0) {
        answer += `<h3>成语错误：</h3><ul>`
        data.idm.forEach((item: any) => {
          answer += `<li>位置：${item[0]}，错误成语：${item[1]}，建议成语：${item[2]}</li>`
        })
        answer += `</ul>`
      }

      if (data.leader.length > 0) {
        answer += `<h3>职称错误：</h3><ul>`
        data.leader.forEach((item: any) => {
          answer += `<li>位置：${item[0]}，错误职称：${item[1]}，建议职称：${item[2]}</li>`
        })
        answer += `</ul>`
      }

      if (data.number.length > 0) {
        answer += `<h3>数字错误：</h3><ul>`
        data.number.forEach((item: any) => {
          answer += `<li>位置：${item[0]}，错误数字：${item[1]}，建议数字：${item[2]}</li>`
        })
        answer += `</ul>`
      }

      if (data.addr.length > 0) {
        answer += `<h3>地名错误：</h3><ul>`
        data.addr.forEach((item: any) => {
          answer += `<li>位置：${item[0]}，错误地名：${item[1]}，建议地名：${item[2]}</li>`
        })
        answer += `</ul>`
      }

      if (data.name.length > 0) {
        answer += `<h3>全文人名错误：</h3><ul>`
        data.name.forEach((item: any) => {
          answer += `<li>位置：${item[0]}，错误人名：${item[1]}，建议人名：${item[2]}</li>`
        })
        answer += `</ul>`
      }

      if (data.grammar_pc.length > 0) {
        answer += `<h3>句式杂糅/语义重复：</h3><ul>`
        data.grammar_pc.forEach((item: any) => {
          answer += `<li>位置：${item[0]}，问题句式：${item[1]}，建议修正：${item[2]}</li>`
        })
        answer += `</ul>`
      }

      if (!answer) {
        answer = '<p>未发现问题</p>'
      }

      setOutput(answer)
    }
  }

  // 存储大模型的回答
  const handleMessageReceived = () => {
    setOutput(totalResRef.current)
  }

  // 点击继续按钮的回调
  const handleNext = () => {
    setOutput('')
    setTextCorr('')
    setResult('')
    setIsEnd(true)
    setLiberty(6)
    ttsWSRef.current?.close()
    if (which === 4) {
      setWhich(2)
    } else if (which === 2) {
      setWhich(1)
    } else if (which === 1) {
      setWhich(3)
    }
  }

  // 大模型是否回答完毕
  const endofJudgment = () => {
    setLoading(false)
  }
  useEffect(() => {
    return () => {
      ttsWSRef.current?.close()
    }
  }, [])

  // 点击询问按钮的回调
  const handleAsk = () => {
    if (asking) {
      setOutput('')
      setTextCorr('')
      setIsEnd(true)
      setLoading(true)

      if (which === 1) {
        setTextCorr(asking)
        rewrite(asking)
        setIsEnd(false)
      } else if (which === 2) {
        textCorrection(asking)
        setTextCorr(asking)
        setIsEnd(false)
      } else if (which === 3) {
        setTextCorr(asking)
        const question: any = `${asking}。这是一道题目，解析一下`
        dialogue(question, ttsWSRef, totalResRef, handleMessageReceived, endofJudgment)
        setIsEnd(false)
      }
      setAsking('')
    } else {
      message.warning('请输入您想问的内容')
    }
  }

  // 回答自由度设置
  const hangleChange: InputNumberProps['onChange'] = (num: any) => {
    setLiberty(num)
  }

  // 页面切换
  const handleClickAvtive = (num: number) => {
    setOutput('')
    setTextCorr('')
    setResult('')
    setIsEnd(true)
    setLiberty(6)
    ttsWSRef.current?.close()
    setWhich(num)
  }

  const [result, setResult] = useState('')

  // 图片上传
  const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      const maxFileSize = 1 * 1024 * 1024 // 1MB
      if (file.size > maxFileSize) {
        message.warning('图片大小不能超过1MB！')
        return
      }

      // 检查文件类型
      const validImageTypes = ['image/jpeg', 'image/png', 'image/gif']
      if (!validImageTypes.includes(file.type)) {
        message.warning('只能上传图片文件！')
        return
      }

      // 创建 FormData 并上传图片
      const formData = new FormData()
      formData.append('file', file)

      try {
        // 执行 OCR 请求
        const reader = new FileReader()
        reader.onloadend = async () => {
          const base64Image = reader.result?.toString().split(',')[1]
          if (base64Image) {
            const apiUrl = 'https://www.tulingyun.com/api/ocr'
            const requestBody = {
              token: 'www.tulingyun.com',
              upfile_b64: base64Image,
              return_text: 0,
              only_rec: 0,
            }

            setResult('正在识别...')
            try {
              const ocrRes = await axios.post(apiUrl, requestBody, {
                headers: {
                  'Content-Type': 'application/json',
                },
              })
              displayResult(ocrRes.data)
            } catch (error: any) {
              setResult(`请求失败: ${error.message}`)
            }
          }
        }
        reader.readAsDataURL(file)
      } catch (error: any) {
        message.error(`上传失败: ${error.message}`)
      }
    }
  }

  const handleChangeImg = () => {
    fileInputRef.current!.click()
  }

  const displayResult = (data: any) => {
    if (data.status_code !== 200000) {
      setResult(`识别失败: ${data.status_message}`)
      return
    }

    let resultHtml = `<h3 style="margin-bottom: 10px">识别结果:</h3>`
    resultHtml += `<p>状态: ${data.msg}</p>`
    resultHtml += `<h4 style="margin: 10px 0">识别文本:</h4>`
    data.text.forEach((text: any, _index: any) => {
      resultHtml += `<div>${text}</div>`
    })

    resultHtml += `<h4 style="margin: 10px 0">置信度:</h4>`
    data.scores.forEach((score: any, index: any) => {
      resultHtml += `<div>文本 ${index + 1} 置信度: ${score}</div>`
    })

    resultHtml += `<h4 style="margin: 10px 0">位置:</h4>`
    data.position.forEach((pos: any, index: any) => {
      resultHtml += `<div>文本 ${index + 1} 位置: ${pos.join(', ')}</div>`
    })

    setResult(resultHtml)
  }

  return (
    <div className="Text">
      {limit.text === 1 ? (
        <div className="text-content">
          <Card className="card">
            <div style={{ display: 'flex', alignItems: 'center' }}>
              {(() => {
                switch (which) {
                  case 1:
                    return <span className="text-font">文本润色</span>
                  case 2:
                    return <span className="text-font">文本纠错</span>
                  case 3:
                    return <span className="text-font">题目解析</span>
                  case 4:
                    return <span className="text-font">文本提取</span>
                }
              })()}
              {which !== 3 && (
                <button
                  onClick={handleNext}
                  className="custom-button"
                  style={{ marginLeft: '20px' }}
                >
                  继续
                </button>
              )}
            </div>
            <div className="circleTabs">
              <div className="circleTabsCircle"></div>

              <div
                style={{ backgroundColor: which === 1 ? '#FD9CBA' : '' }}
                className="circleTabsItem1"
                onClick={() => {
                  handleClickAvtive(1)
                }}
              >
                <div>
                  <SvgIcon name="polish" size="20"></SvgIcon>
                </div>
              </div>
              <div
                onClick={() => {
                  handleClickAvtive(2)
                }}
                style={{ backgroundColor: which === 2 ? '#FD9CBA' : '' }}
                className="circleTabsItem2"
              >
                <div>
                  <SvgIcon name="errCorr" size="20"></SvgIcon>
                </div>
              </div>
              <div
                onClick={() => {
                  handleClickAvtive(3)
                }}
                style={{ backgroundColor: which === 3 ? '#FD9CBA' : '' }}
                className="circleTabsItem3"
              >
                <div>
                  <SvgIcon name="analyze2" size="20"></SvgIcon>
                </div>
              </div>
              <div
                onClick={() => {
                  handleClickAvtive(4)
                }}
                style={{ backgroundColor: which === 4 ? '#FD9CBA' : '' }}
                className="circleTabsItem4"
              >
                <div>
                  <SvgIcon name="textRec" size="20"></SvgIcon>
                </div>
              </div>
            </div>
            {which === 4 ? (
              <div className="imgGenText">
                <p style={{ fontWeight: '600', color: 'red', margin: '20px 0' }}>
                  将选择的图片上传，提取出其中的文字信息
                </p>
                <input
                  type="file"
                  ref={fileInputRef}
                  id="image-file"
                  accept="image/*"
                  onChange={handleFileChange}
                  style={{ display: 'none' }}
                />
                <button onClick={handleChangeImg} className="custom-button">
                  选择图片并上传
                </button>

                <div
                  className="result"
                  style={{
                    marginTop: '20px',
                  }}
                  dangerouslySetInnerHTML={{ __html: result }}
                ></div>
              </div>
            ) : (
              <div className="insideCard">
                <Input
                  value={asking}
                  onKeyDown={(e) => {
                    e.key === 'Enter' && handleAsk()
                  }}
                  onChange={(e) => setAsking(e.target.value)}
                  size="large"
                  className="cardInput"
                  addonAfter={<SearchOutlined onClick={handleAsk} />}
                  placeholder="请输入您要模型处理的内容"
                  prefix={<WindowsOutlined />}
                ></Input>
                {which === 1 && (
                  <InputNumber
                    min={1}
                    max={6}
                    defaultValue={6}
                    changeOnWheel
                    size="large"
                    onChange={hangleChange}
                    className="answer-inputNum"
                  ></InputNumber>
                )}
                {!isEnd && (
                  <div className="answer">
                    <div className="answerText">
                      我的问题：<span>{textCorr}</span>
                    </div>
                    <div className="answer-content">
                      <img src="/assets/images/IFlytek.png" alt="" />
                      {loading && (
                        <div className="wrapper">
                          <div className="circle"></div>
                          <div className="circle"></div>
                          <div className="circle"></div>
                          <div className="shadow"></div>
                          <div className="shadow"></div>
                          <div className="shadow"></div>
                          <span>玩命加载中。。。</span>
                        </div>
                      )}
                      <div
                        style={{ marginTop: '5px' }}
                        dangerouslySetInnerHTML={{ __html: output }}
                      ></div>
                    </div>
                  </div>
                )}
              </div>
            )}
          </Card>
        </div>
      ) : (
        <div style={{ marginTop: '35vh', fontSize: '30px', color: 'red', fontWeight: '600' }}>
          没有使用权限
        </div>
      )}
    </div>
  )
}

export default Text
